import * as React from 'react';
import { Col, Row, Menu } from 'antd'
import ArticleList from '../../components/ArticleList/ArticleList'
import Pubsub from 'pubsub-js';
import Advert from '../../components/Advert/Advert'
import './ArticleCateory.less'
import { article } from '../Home/Home';
import { RouteComponentProps } from 'react-router-dom';
import { reqArticles } from '../../axios';

export interface ArticleCateoryProps extends RouteComponentProps {

}

export interface ArticleCateoryState {
  articles: article[]
  path: string
  clickCount: number
  articlesCount: number
  isAll: Boolean

}
class ArticleCateory extends React.Component<ArticleCateoryProps, ArticleCateoryState> {
  orderBy : string = 'create_time' //根据哪个字段排序
  state = {
    articles: [],
    path: '',
    clickCount: 0,
    articlesCount: 0,
    isAll: false // 是否是全部文章列表用来判断是否显示加载更多按钮
  }
  componentDidUpdate(prevProps: ArticleCateoryProps, prevState: ArticleCateoryState) {
    if (prevState.path !== this.props.location.pathname) {
      //@ts-ignore
      const { categoryId } = this.props.match.params;
     
      this.setState({ path: this.props.location.pathname,clickCount:0,isAll:false },()=>{
        this.handleOrder('create_time', 'desc', categoryId);
      })
    }
  }
  componentDidMount() {
    //@ts-ignore
    const { categoryId } = this.props.match.params;
    Pubsub.subscribe('clickCount', () => {      
      //统计一下点击加载更多按钮的次数 为显示条数做准备
      this.setState({ clickCount: this.state.clickCount+1 }, () => {
        this.handleOrder(this.orderBy, 'desc', categoryId);        
      })
    })
    //根据地址栏的id 查找对应分类的文章列表
    if (this.state.articles.length <= 0) {
      this.handleOrder('create_time', 'desc', categoryId);
    }
  }
  componentWillUnmount(){
    PubSub.unsubscribe('clickCount');
  }

  //请求排序之后的文章
  handleOrder = async (field: string, order: string, categoryId: number, pageSize = 4, pageNum = 1) => {
      try {
          const response = await reqArticles({pageNum: pageNum + this.state.clickCount,pageSize, searchEntity: { category_id: categoryId }, orderEntity: { 'is_top': 'asc', [field]: order } });
          const articles = response.data.data.records;
        //记录文章的总数        
        this.setState({ articlesCount: response.data.data.total }, () => {
          if (this.state.articlesCount <= (pageNum + this.state.clickCount) * pageSize) {
            this.setState({ isAll: true })
          }
        })
        if (this.state.clickCount === 0) {          
          this.setState({ articles })
        } else {
          console.log();
          
          //加载更多
          this.setState((state) => ({
            articles: [...state.articles, ...response.data.data.records]
          }))
        }
       
      } catch (error) {
          console.log(error);
      }
  }
  //点击头部进行排序
  handleSort = (orderBy:string) =>{
    //@ts-ignore
    const { categoryId } = this.props.match.params;
    this.setState({clickCount:0,isAll:false},()=>{
      this.orderBy=orderBy;
      this.handleOrder(orderBy, 'desc', categoryId);
    })
   
  }

  render() {
    
    const { articles,isAll } = this.state;
    const header = (
      <Menu mode='horizontal'>
        <Menu.Item onClick={() => this.handleSort('create_time')}>
          最新
                  </Menu.Item>
        <Menu.Item onClick={() => this.handleSort('read')}>
          热门
                </Menu.Item>
      </Menu>
    )
    return (
      <>
        <div className='home-main'>
          <div className='article-banner'></div>
          <Row justify='center'>
            <Col className='home-main-left' xs={24} sm={24} md={24} lg={18} xl={18}>
              <ArticleList isAll={isAll} header={header} articles={articles}></ArticleList>
            </Col>
            <Col className='home-main-right' xs={0} sm={0} md={0} lg={6} xl={6}>
              <Advert></Advert>
            </Col>
          </Row>
        </div>
      </>);
  }
}

export default ArticleCateory;